<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Model\UserLoginModel;
use App\Model\UserModel;
use App\Model\UserWalletModel as UserWallet;
use App\Model\UserModel as User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Cache;
use Mockery\Expectation;
use Mail;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use QrCode;


class LoginController extends Controller
{
	//注册
	public function register()
	{
		//云仓号
		$pid = 0;
		$path = '0,';
		if(request()->invite_code){
			$puser = User::where('invite_code', request()->invite_code)->first();
			if (!$puser) {
				return ['code' => 0, 'msg' => retStrInfo(1)];
			}
			$pid = $puser['id'];
			$path = $puser['path'].$pid.",";

		}
		//昵称
		if(!request()->user){
			return ['code'=>0,'msg'=>retStrInfo(2)];
		}
		$str_user ='/[\'.,:;*?~`!@#$%^&+=)(<>{}]|5261\]|\[|\/|\\\|\"|\|/';
		if(preg_match($str_user,request()->user)){
			return ['code'=>0,'msg'=>'昵称不可包含特殊字符'];
		}
		$user_len = mb_strlen(request()->user,'UTF8');
	
		if($user_len > 15){
			return ['code'=>0,'msg'=>"请输入15位以内的昵称"];
		}
		if(User::where('user',request()->user)->first()){
			return ['code'=>0,'msg'=>retStrInfo(3)];
		}
		//type 1手机号 2邮箱
		$phone = '';
		$email = '';
		$str_phone = '/^[1]\\d{10}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';
		if(request()->type == 1){
			if (!preg_match($str_phone, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(4)];
			}
			$user = User::where('phone', request()->username)->first();
			$phone = request()->username;
		}else{
			if (!preg_match($str_email, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(5)];
			}
			$user = User::where('email', request()->username)->first();
			$email = request()->username;
		}
		//账号是否存在
		if ($user) {
			return ['code' => 0, 'msg' => retStrInfo(6)];
		}
		// //验证码
		$str = '/^\\d{6}$/';
		if (!preg_match($str, request()->code)) {
			return ['code' => 0, 'msg' => retStrInfo(7)];
		}
		$code = Cache::get(request()->username);
		if ($code != request()->code) {
			return ['code' => 0, 'msg' => retStrInfo(8)];
		}
		//密码

		if (!request()->password) {
			return ['code' => 0, 'msg' => retStrInfo(9)];
		}
		//判断是否包含中文
		$str_pass = '/[\x7f-\xff]/';
		if(preg_match($str_pass,request()->password)){
			return ['code'=>0,'msg'=>"密码不能包含中文字符"];
		}
		
		if(strlen(request()->password) > 16 || strlen(request()->password) < 6){
			return ['code'=>0,'msg'=>"请输入长度为6~16位的密码"];
		}
		$str_pay = '/^\\d{6}$/';
		//支付密码
		if (!preg_match($str, request()->paypass)) {
			return ['code' => 0, 'msg' => retStrInfo(10)];
		}
		if (!preg_match($str_pay, request()->paypass)) {
			return ['code' => 0, 'msg' => '请输入6位数字的支付密码'];
		}
		if(request()->area_code){
			$area_code = request()->area_code;
		}else{
			$area_code = '+86';
		}
		DB::beginTransaction();
		try {
			if(request()->invite_code){
				$pids = explode(',',$path);
				foreach($pids as $k=>$v){
					User::where('id',$v)->increment('team');
				}
				User::where('id',$pid)->increment('push');
			}
		
			do {
				$invite_cy = UserModel::orderBy('id','desc')->first();
				$invite_code = zero($invite_cy['invite_code'] +1);
	
			} while (User::where('invite_code', $invite_code)->first());
	

			$auth_name = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
			if (preg_match($auth_name, request()->user)) {
				$pin = app('pinyin');
				$pinyin =$pin->abbr(request()->user);
			}else{
				$pinyin = request()->user;
			}
			//首字母
			$head = pinying($pinyin);
			$user = User::create([
				'phone' => $phone,
				'email' => $email,
				'password' => Hash::make(request()->password),
				'paypass' => Hash::make(request()->paypass),
				'pid' => $pid,
				'path' => $path,
				'user' => request()->user,
				'invite_code' => $invite_code,
				'area_code' => $area_code,
				'login_type' => request()->type,
				'head' => $head,
			]);
			$user->generateToken();
			UserWallet::create([
				'uid'=>$user->id,
			]);

            $img = $user['invite_code'].'.png';
			$qrCode = new \Endroid\QrCode\QrCode('http://' . request()->getHost() . '/invite_own?invite=' . $user['invite_code']);
			$qrCode->setSize(300);
			$qrCode->writeFile(public_path() . "/upload/invite/".$img);
			$bigImgPath = public_path() . '/upload/invite/invite.png';
			$qCodePath = public_path() . "/upload/invite/".$img;
			$bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
			$qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
			list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
			imagecopymerge($bigImg, $qCodeImg, 230, 670, 0, 0, $qCodeWidth, $qCodeHight, 100);
			list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);
			$textcolor = imagecolorallocate($bigImg, 255, 140, 25);
			imagettftext($bigImg,  52, 0, 250, 582, $textcolor, public_path() . '/myfont.ttf', $user['invite_code']);
			imagepng($bigImg, public_path() . "/upload/invite/".$img);
			
			DB::commit();
			Cache::pull(request()->username);
			$data['id'] = $user['id'];
			$data['token'] = $user['token'];
			return ['code' => 1, 'msg' => retStrInfo(11),'data'=>$data];
		} catch (Expectation $e) {
			DB::rollback();
			return ['code' => 0, 'msg' => retStrInfo(12)];
		}
	}

	//登陆
	public function login()
	{
		//判断账户/邮箱格式是否正确
		$str_phone = '/^1[3456789]\d{9}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';
		if(request()->type == 1){
			if (!preg_match($str_phone, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(4)];
			}
			$user = User::where('phone', request()->username)->first();
		}else{
			if (!preg_match($str_email, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(5)];
			}
			$user = User::where('email', request()->username)->first();
		}
		//判断该账户是否存在
		if (!$user) {
			return ['code' => 0, 'msg' => retStrInfo(13)];
		}
		//密码
		if (!request()->password) {
			return ['code' => 0, 'msg' => retStrInfo(9)];
		}
		//判断密码是否输入正确
		if (!Hash::check(request()->password, $user->password)) {
			return ['code' => 0, 'msg' => retStrInfo(14)];
		}
		//判断账户是否冻结
		if($user->state == 2){
			return ['code' => 0, 'msg' => retStrInfo(15)];
		}

		//更改token
		$user->generateToken();
		$data['id'] = $user['id'];
		$data['token'] = $user['token'];
		$data['user'] = $user['user'];
		$data['is_auth'] = $user['is_auth'];
		$data['invite_code'] = $user['invite_code'];
//		if(empty($user['picname'])){
//			$data['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
//		}else{
//			$data['picname'] = "http://".$_SERVER['HTTP_HOST'].$user['picname'];
//		}

		//用户是否第三方
		$party = UserLoginModel::where('uid',$user['id'])->first();
//		if($party['picname']){
//			$data['picname'] = $party['picname'];
//		}else{
//			if(empty($users['picname'])){
//				$data['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
//			}else{
//				$data['picname'] = "http://".$_SERVER['HTTP_HOST'].$users['picname'];
//			}
//		}

		if(empty($user['picname'])){

			if(empty($party['picname'])){
				$data['picname'] = "http://".$_SERVER['HTTP_HOST']."/user.png";
			}else{
				$data['picname'] = $party['picname'];
			}
		}else{
			$data['picname'] = "http://".$_SERVER['HTTP_HOST'].$user['picname'];
		}
		return ['code' => 1,'msg'=>retStrInfo(96),'data'=>$data];
	}

	//忘记密码
	public function forget()
	{
		//判断账户/邮箱格式是否正确
		$str_phone = '/^[1]\\d{10}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';
		if(request()->type == 1){
			if (!preg_match($str_phone, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(4)];
			}
			$user = User::where('phone', request()->username)->first();
		}else{
			if (!preg_match($str_email, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(5)];
			}
			$user = User::where('email', request()->username)->first();
		}
		//判断该账户是否存在
		if (!$user) {
			return ['code' => 0, 'msg' => retStrInfo(13)];
		}

		//验证码
		$str = '/^\\d{6}$/';
		if (!preg_match($str, request()->code)) {
			return ['code' => 0, 'msg' => retStrInfo(7)];
		}
		$code = Cache::get(request()->username);
		if ($code != request()->code) {
			return ['code' => 0, 'msg' => retStrInfo(8)];
		}

		if (!request()->password) {
			return ['code' => 0, 'msg' => retStrInfo(9)];
		}
		if(!request()->sure_pass){
			return ['code' => 0, 'msg' => retStrInfo(16)];
		}
		if(request()->password != request()->sure_pass){
			return ['code' => 0, 'msg' => retStrInfo(16)];
		}

		$data = [];
		DB::beginTransaction();
		try {
			//安全密码
			$user->update([
				'password' => Hash::make(request()->password),
			]);

			$data['id'] = $user->id;
			$data['token'] = $user->token;

			DB::commit();
			Cache::pull(request()->username);
			return ['code' => 1, 'msg' => retStrInfo(17),'data'=>$data];
		} catch (Expectation $e) {
			DB::rollBack();
			return ['code' => 0, 'msg' => retStrInfo(18)];
		}
	}

	//发送验证码
	public function send_code()
	{
		$str_phone = '/^1[2,3,4,5,6,7,8,9]\d{9}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';
		//1 注册账号,重新绑定手机号,邮箱
		if (request()->flag == 1) {
			//1手机号, 2邮箱
			if(request()->type ==1){
				if (!request()->username){
					return ['code' => 0, 'msg' => retStrInfo(26)];
				}
				if (!preg_match($str_phone, request()->username)) {
					return ['code' => 0, 'msg' => retStrInfo(4)];
				}
				$user = User::where('phone', request()->username)->first();
				if ($user) {
					return ['code' => 0, 'msg' => retStrInfo(28)];
				}
			}else{
				if (!preg_match($str_email, request()->username)) {
					return ['code' => 0, 'msg' => retStrInfo(5)];
				}
				$user = User::where('email', request()->username)->first();
				if ($user) {
					return ['code' => 0, 'msg' => retStrInfo(29)];
				}
			}
			//手机号登录
			if(request()->type == 1){
				if(request()->area_code){
					if(request()->area_code != '+86'){
						Cache::put(request()->username,888888);
						return ['code' => 1, 'msg' => retStrInfo(30)];
					}
				}
				return $this->sendCode(request()->username);

//				if(request()->area_code != '+86'){
//
//					Cache::put(request()->username,888888);
//					return ['code' => 1, 'msg' => retStrInfo(30)];
//				}else{
//					return $this->sendCode(request()->username);
//				}
				//邮箱登录
			}else{
				return $this->sendEmail(request()->username);
			}
			//2忘记密码
		} elseif (request()->flag == 2) {

			if(request()->type == 1){
				$user = User::where('phone',request()->username)->first();
			}else{
				$user = User::where('email',request()->username)->first();
			}
			if (!$user) {
				return ['code' => 0, 'msg' => retStrInfo(13)];
			}
			if ($user->login_type == 2) {
				return $this->sendEmail(request()->username);
			}else{
				if($user->area_code == '+86'){
					return $this->sendCode(request()->username);
				}else{
					Cache::put(request()->username,888888);
					return ['code' => 1, 'msg' => retStrInfo(30)];
				}
			}
			//修改密码,二级密码
		}elseif(request()->flag == 3){
			$user = User::where('id',request()->header('uid'))->first();
			if (!$user) {
				return ['code' => 0, 'msg' => retStrInfo(13)];
			}
			if($user->login_type == 1){
				if($user->area_code == '+86'){
					return $this->sendCode($user->phone);
				}else{
					Cache::put($user->phone,888888);
					return ['code' => 1, 'msg' => retStrInfo(30)];
				}
			}else{
				return $this->sendEmail($user->email);
			}
		}
	}

	//发送验证码
	public function sendCode($phone){
		error_reporting(0);
		try {
			AlibabaCloud::accessKeyClient(env('ALIYUN_ACCESS_KEY_ID',"LTAI4FuutUj3UmRQbv1WNdwp"), env('ALIYUN_ACCESS_KEY_SECRET'))
				->regionId(env('ALIYUN_REGION_ID'))
				->asDefaultClient();

			$code= rand(111111,999999);
			$result = AlibabaCloud::rpc()
				->product('Dysmsapi')
				->version(env('ALIYUN_VERSION'))
				->action('SendSms')
				->method('POST')
				->host(env('ALIYUN_HOST'))
				->options([
					'query' => [
						'RegionId' => env('ALIYUN_ACCESS_KEY_ID'),
						'SignName' => env('ALIYUN_SIGN_NAME'), //必填项 签名(需要在阿里云短信服务后台申请)
						'TemplateCode' => env('ALIYUN_TEMPLATE_CODE'),//必填项 短信模板code (需要在阿里云短信服务后台申请)
						'TemplateParam' => "{'code':$code}",//如果在短信中添加了${code} 变量则此项必填 要求为JSON格式
						'PhoneNumbers' => $phone, //需要发送到那个手机
					],
				])
				->request();
			if($result->Code == 'OK'){
				Cache::put($phone,$code);
				$code = Cache::get($phone);
				return ['code' => 1, 'msg' => retStrInfo(30)];
			}else{
				return ['code' => 0, 'msg' => retStrInfo(31)];
			}
		} catch (ClientException $e) {
			return ['code' => 0, 'msg' => retStrInfo(31)];
		}
	}

	//发送邮箱
	public function sendEmail($phone){
		$code = rand(100000,999999);
        $a = "尊敬的用户: 验证码:".$code."（提示：工作人员不会索要，切勿泄露！）";
		$this->email = $phone;
		Mail::raw($a,function($message){
			$to = $this->email;
			$message->to($to)->subject('云仓库');
		});
		$this->email = '';
		Cache::put($phone,$code);
		return ['code' => 1, 'msg' => retStrInfo(30)];
	}

	//第三方发送验证码
	public function party_code(){
		$str_phone = '/^[1]\\d{10}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';
		//手机号
		if(request()->type == 1){
			if (!preg_match($str_phone, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(4)];
			}
			$user = UserModel::where('phone',request()->username)->first();
			//邮箱
		}else{
			if (!preg_match($str_email, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(5)];
			}
			$user = UserModel::where('phone', request()->username)->first();
		}
		//判断用户是否存在
		if($user){
			//查询是否第三方登录
			$is_exit = UserLoginModel::where('uid',$user['id'])->where('type',request()->partyid)->first();
			if($is_exit){
				return ['code' => 0, 'msg' => retStrInfo(6)];
			}
		}
		if(request()->type == 1){
			if(request()->area_code == '+86'){
				return $this->sendCode(request()->username);
			}else{
				Cache::put(request()->username,888888);
				return ['code'=>1,'msg'=>retStrInfo(30)];
			}
		}else{
			return $this->sendEmail(request()->username);
		}
	}

	//测试
	public function test_q(){
		$user = User::where('id','<>','2')->get();
		// $user = User::where('id',27)->first();
		foreach($user as $k=>$v){
			$invite_code = zero($k+1);
			User::where('id',$v['id'])->update(['invite_code'=>$invite_code]);
			$v['invite_code'] = User::where('id',$v['id'])->value('invite_code');

			$img = $v['invite_code'].'.png';
			UserModel::where('id',$v['id'])->update(['invite_code'=>$v['invite_code']]);
			$qrCode = new \Endroid\QrCode\QrCode('http://' . request()->getHost() . '/invite_own?invite=' . $v['invite_code']);
			$qrCode->setSize(300);
			$qrCode->writeFile(public_path() . "/upload/invite/".$img);
			$bigImgPath = public_path() . '/upload/invite/invite.png';
			$qCodePath = public_path() . "/upload/invite/".$img;
			$bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
			$qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
			list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
			imagecopymerge($bigImg, $qCodeImg, 230, 670, 0, 0, $qCodeWidth, $qCodeHight, 100);
			list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);
			$textcolor = imagecolorallocate($bigImg, 255, 140, 25);
			imagettftext($bigImg, 52, 0, 250, 582, $textcolor, public_path() . '/myfont.ttf', $v['invite_code']);
			imagepng($bigImg, public_path() . "/upload/invite/".$img);
		}
	}

	// public function test_q(){
	// 	$user = User::where('id','<>','2')->get();
	// 	// $user = User::where('id',27)->first();
	// 	foreach($user as $k=>$v){
	// 		$invite_code = zero($k+1);
	// 		User::where('id',$v['id'])->update(['invite_code'=>$invite_code]);
	// 		$v['invite_code'] = User::where('id',$v['id'])->value('invite_code');

	// 		$img = $v['invite_code'].'.png';
	// 		UserModel::where('id',$v['id'])->update(['invite_code'=>$v['invite_code']]);
	// 		$qrCode = new \Endroid\QrCode\QrCode('http://' . request()->getHost() . '/invite_own?invite=' . $v['invite_code']);
	// 		$qrCode->setSize(300);
	// 		$qrCode->writeFile(public_path() . "/upload/invite/".$img);
	// 		$bigImgPath = public_path() . '/upload/invite/invite.png';
	// 		$qCodePath = public_path() . "/upload/invite/".$img;
	// 		$bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
	// 		$qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
	// 		list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
	// 		imagecopymerge($bigImg, $qCodeImg, 230, 670, 0, 0, $qCodeWidth, $qCodeHight, 100);
	// 		list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);
	// 		$textcolor = imagecolorallocate($bigImg, 255, 140, 25);
	// 		imagettftext($bigImg, 52, 0, 250, 582, $textcolor, public_path() . '/myfont.ttf', $v['invite_code']);
	// 		imagepng($bigImg, public_path() . "/upload/invite/".$img);
	// 	}
	// }
}
